const app = getApp();
var util = require('../../../utils/util.js');

Page({
    data: {
        projectId: null,
        projectName: '',
        projectAmount: 0,
        members: [],
        totalAmount: 0,
        // 弹窗相关
        showModal: false,
        newMember: {
            nickname: '',
            phone: '',
            amount: '',
            remark: ''
        },
        isEditing: false,
        editingMemberId: null
    },
    
    onLoad: function(options) {
        // 设置导航栏标题
        wx.setNavigationBarTitle({
            title: '成员管理'
        });
        
        if (options.id) {
            this.setData({
                projectId: options.id
            });
            
            // 加载项目信息和成员列表
            this.loadProjectData();
        } else {
            wx.showToast({
                title: '项目ID不存在',
                icon: 'none',
                success: () => {
                    setTimeout(() => {
                        wx.navigateBack();
                    }, 1500);
                }
            });
        }
    },
    
    // 加载项目数据
    loadProjectData: function() {
        wx.showLoading({
            title: '加载中...',
        });
        
        util.httpRrquest(app.data.rooturl + 'user/getProjectInfo', 'GET', {
            projectId: this.data.projectId
        })
        .then(response => {
            wx.hideLoading();
            
            if (response.data.code === 1) {
                const projectData = response.data.data;
                // 计算总分润金额和剩余可分配金额
                const totalAmount = projectData.member.reduce((sum, member) => sum + parseFloat(member.money || 0), 0);
                
                this.setData({
                    projectName: projectData.name,
                    projectAmount: projectData.allMoney,
                    members: projectData.member || [],
                    totalAmount: totalAmount
                });
            } else {
                wx.showToast({
                    title: response.data.msg || '加载失败',
                    icon: 'none'
                });
            }
        })
        .catch(error => {
            wx.hideLoading();
            console.error('请求失败', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        });
    },
    
    // 显示添加成员弹窗
    showAddMemberModal: function() {
        this.setData({
            showModal: true,
            isEditing: false,
            editingMemberId: null,
            newMember: {
                nickname: '',
                phone: '',
                amount: '',
                remark: ''
            }
        });
    },
    
    // 显示编辑成员弹窗
    editMember: function(e) {
        const { id, nickname, phone, amount, remark } = e.currentTarget.dataset;
        console.log(id, nickname, phone, amount, remark);
        this.setData({
            showModal: true,
            isEditing: true,
            editingMemberId: id,
            newMember: {
                nickname: nickname || '',
                phone: phone || '',
                amount: amount || '',
                remark: remark || ''
            }
        });
    },
    
    // 更新成员信息
    updateMember: function() {
        const { newMember, editingMemberId } = this.data;
        
        // 表单验证
        
        if (!newMember.phone) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none'
            });
            return;
        }
        
        // 验证手机号格式
        if (!/^1\d{10}$/.test(newMember.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }
        
        if (!newMember.amount) {
            wx.showToast({
                title: '请输入分润金额',
                icon: 'none'
            });
            return;
        }
        
        // 验证分润金额
        const amount = parseFloat(newMember.amount);
        if (isNaN(amount) || amount <= 0) {
            wx.showToast({
                title: '请输入有效的分润金额',
                icon: 'none'
            });
            return;
        }
        
        // 提交更新成员请求
        wx.showLoading({
            title: '更新中...',
        });
        
        util.httpRrquest(app.data.rooturl + 'user/updateMember', 'POST', {
            projectId: this.data.projectId,
            memberId: editingMemberId,
            phone: newMember.phone,
            amount: amount,
            remark: newMember.remark || ''
        })
        .then(response => {
            wx.hideLoading();
            
            if (response.data.code === 1) {
                wx.showToast({
                    title: '更新成功',
                    icon: 'success'
                });
                
                // 重新加载数据
                this.loadProjectData();
                
                // 关闭弹窗
                this.hideModal();
            } else {
                wx.showToast({
                    title: response.data.msg || '更新失败',
                    icon: 'none'
                });
            }
        })
        .catch(error => {
            wx.hideLoading();
            console.error('请求失败', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        });
    },
    
    // 隐藏弹窗
    hideModal: function() {
        this.setData({
            showModal: false
        });
    },
    
    // 输入成员昵称
    inputMemberName: function(e) {
        this.setData({
            'newMember.nickname': e.detail.value
        });
    },
    
    // 输入成员手机号
    inputMemberPhone: function(e) {
        this.setData({
            'newMember.phone': e.detail.value
        });
    },
    
    // 输入分润金额
    inputMemberAmount: function(e) {
        this.setData({
            'newMember.amount': e.detail.value
        });
    },
    
    // 输入备注信息
    inputMemberRemark: function(e) {
        this.setData({
            'newMember.remark': e.detail.value
        });
    },
    
    // 添加成员
    addMember: function() {
        const { newMember, remainingAmount } = this.data;
        
        // 表单验证
        
        
        if (!newMember.phone) {
            wx.showToast({
                title: '请输入手机号',
                icon: 'none'
            });
            return;
        }
        
        // 验证手机号格式
        if (!/^1\d{10}$/.test(newMember.phone)) {
            wx.showToast({
                title: '请输入正确的手机号',
                icon: 'none'
            });
            return;
        }
        
        if (!newMember.amount) {
            wx.showToast({
                title: '请输入分润金额',
                icon: 'none'
            });
            return;
        }
        
        // 验证分润金额
        const amount = parseFloat(newMember.amount);
        if (isNaN(amount) || amount <= 0) {
            wx.showToast({
                title: '请输入有效的分润金额',
                icon: 'none'
            });
            return;
        }
        
        // 验证分润金额不超过剩余可分配金额
        if (amount > remainingAmount) {
            wx.showToast({
                title: '分润金额不能超过剩余可分配金额',
                icon: 'none'
            });
            return;
        }
        
        // 提交添加成员请求
        wx.showLoading({
            title: '添加中...',
        });
        
        util.httpRrquest(app.data.rooturl + 'user/addMember', 'POST', {
            projectId: this.data.projectId,
            phone: newMember.phone,
            amount: amount,
            remark: newMember.remark || ''
        })
        .then(response => {
            wx.hideLoading();
            
            if (response.data.code === 1) {
                wx.showToast({
                    title: '添加成功',
                    icon: 'success'
                });
                
                // 重新加载数据
                this.loadProjectData();
                
                // 关闭弹窗
                this.hideModal();
            } else {
                wx.showToast({
                    title: response.data.msg || '添加失败',
                    icon: 'none'
                });
            }
        })
        .catch(error => {
            wx.hideLoading();
            console.error('请求失败', error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        });
    },
    
    // 删除成员
    deleteMember: function(e) {
        const memberId = e.currentTarget.dataset.id;
        
        wx.showModal({
            title: '提示',
            content: '确定要删除该成员吗？',
            success: (res) => {
                if (res.confirm) {
                    // 提交删除成员请求
                    wx.showLoading({
                        title: '删除中...',
                    });
                    
                    util.httpRrquest(app.data.rooturl + 'user/deleteMember', 'POST', {
                        projectId: this.data.projectId,
                        memberId: memberId
                    })
                    .then(response => {
                        wx.hideLoading();
                        
                        if (response.data.code === 1) {
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success'
                            });
                            
                            // 重新加载数据
                            this.loadProjectData();
                        } else {
                            wx.showToast({
                                title: response.data.msg || '删除失败',
                                icon: 'none'
                            });
                        }
                    })
                    .catch(error => {
                        wx.hideLoading();
                        console.error('请求失败', error);
                        wx.showToast({
                            title: '网络错误，请重试',
                            icon: 'none'
                        });
                    });
                }
            }
        });
    },
    
    // 提交成员信息
    submitMembers: function() {
        // 显示确认对话框
        wx.showModal({
            title: '提示',
            content: '确定要提交成员信息吗？',
            success: (res) => {
                if (res.confirm) {
                    // 用户点击确定，继续提交
                    wx.showLoading({
                        title: '提交中...',
                    });
                    
                    util.httpRrquest(app.data.rooturl + 'user/submitProjectMembers', 'POST', {
                        projectId: this.data.projectId
                    })
                    .then(response => {
                        wx.hideLoading();
                        
                        if (response.data.code === 1) {
                            wx.showToast({
                                title: '提交成功',
                                icon: 'success',
                                success: () => {
                                    // 延迟返回上一页
                                    setTimeout(() => {
                                        wx.navigateBack();
                                    }, 1500);
                                }
                            });
                        } else {
                            wx.showToast({
                                title: response.data.msg || '提交失败',
                                icon: 'none'
                            });
                        }
                    })
                    .catch(error => {
                        wx.hideLoading();
                        console.error('请求失败', error);
                        wx.showToast({
                            title: '网络错误，请重试',
                            icon: 'none'
                        });
                    });
                }
                // 用户点击取消，不做任何操作
            }
        });
    }
});